<script setup lang="ts">
import { ref, h, onMounted, computed, reactive } from "vue";
import { useColumns } from "./columns";
import { IconifyIconOnline } from "@/components/ReIcon";
import { PlusDialogForm } from "plus-pro-components";
import type {
  PlusColumn,
  FieldValues,
  PlusFormInstance
} from "plus-pro-components";
import { message } from "@/utils/message";
import {
  dayjs,
  ElImage,
  ElInput,
  ElTag,
  ElRadioGroup,
  ElRadioButton,
  ElDescriptions,
  ElDescriptionsItem
} from "element-plus";
import { Address, OrderItem } from "types/order";
import ProductList from "./components/ProductList.vue";
import numeral from "numeral";
import { getAllDeliveryPerson } from "@/api/delivery-person";
import { DeliveryPerson } from "types/delivery-person";
import {
  closeOrder,
  completeOrder,
  deliveryOrder,
  getOrderDetail,
  refundOrder
} from "@/api/order";

const SERVER_URL = import.meta.env.VITE_SERVER_URL;

const tableRef = ref();

const {
  loading,
  columns,
  dataList,
  pagination,
  loadingConfig,
  adaptiveConfig,
  filter,
  onSizeChange,
  onCurrentChange,
  reload,
  refresh,
  search
} = useColumns({
  onEdit: (row, index) => {
    formData.value = { ...row };

    formVisible.value = true;
  }
});

const formRules = {};

const state = reactive<{
  formLoadingBtn: "delivery" | "close" | "complete" | "refund" | null;
}>({
  formLoadingBtn: null
});

const formColumns: PlusColumn[] = [
  {
    label: "订单号",
    prop: "order_code",
    valueType: "input",
    colProps: {
      span: 12
    },
    fieldProps: {
      readonly: true
    }
  },
  {
    label: "订单金额",
    prop: "total_price",
    valueType: "input",
    colProps: {
      span: 12
    },
    renderField(value: number, onChange) {
      return h(ElInput, {
        modelValue: "￥" + numeral(value).format("0.00"),
        readonly: true
      });
    }
  },
  {
    label: "客户昵称",
    prop: "customer.nickname",
    valueType: "input",
    colProps: {
      span: 12
    },
    fieldProps: {
      readonly: true
    }
  },
  {
    label: "联系电话",
    prop: "customer_phone",
    valueType: "input",
    colProps: {
      span: 12
    },
    fieldProps: {
      readonly: true
    }
  },
  {
    label: "配送方式",
    prop: "delivery_method",
    valueType: "radio",
    renderField(value: number, onChange) {
      return h(ElRadioGroup, { modelValue: value }, [
        h(ElRadioButton, { label: "配送", value: 1, disabled: value === 2 }),
        h(ElRadioButton, { label: "自提", value: 2, disabled: value === 1 })
      ]);
    },
    colProps: {
      span: 12
    }
  },
  {
    label: "配送/自提时间",
    prop: "delivery_date",
    renderField(value: string | undefined, onChange) {
      return h(ElInput, {
        modelValue: value
          ? dayjs(value).format("YYYY-MM-DD HH:mm")
          : "立即处理",
        readonly: true
      });
    },
    colProps: {
      span: 12
    }
  },
  {
    label: "支付状态",
    prop: "payment_status",
    colProps: {
      span: 8
    },
    renderField(value: number) {
      switch (value) {
        case 1:
          return h(ElTag, { type: "danger" }, "待支付");
        case 2:
          return h(ElTag, { type: "success" }, "已支付");
        case 3:
          return h(ElTag, { type: "warning" }, "已退款");
        default:
          return h(ElTag, { type: "info" }, "未知");
      }
    }
  },
  {
    label: "配送状态",
    prop: "shipping_status",
    colProps: {
      span: 8
    },
    renderField(value: number) {
      switch (value) {
        case 1:
          return h(ElTag, { type: "danger" }, "待发货");
        case 2:
          return h(ElTag, { type: "warning" }, "配送中");
        case 3:
          return h(ElTag, { type: "success" }, "已完成");
        default:
          return h(ElTag, { type: "info" }, "未知");
      }
    }
  },
  {
    label: "订单状态",
    prop: "status",
    colProps: {
      span: 8
    },
    renderField(value: number) {
      switch (value) {
        case 1:
          return h(ElTag, { type: "warning" }, "进行中");
        case 2:
          return h(ElTag, { type: "success" }, "已完成");
        case 3:
          return h(ElTag, { type: "info" }, "已取消");
        default:
          return h(ElTag, { type: "info" }, "未知");
      }
    }
  },
  {
    label: "送货地址",
    prop: "delivery_address",
    valueType: "textarea",
    renderField(value: Address, onChange) {
      const text = `${value.recipient} ${value.phone}\n区域范围：${value.province}-${value.city}-${value.district}\n详细地址：${value.details_address}`;
      return h(ElInput, {
        type: "textarea",
        modelValue: text,
        readonly: true,
        autosize: true
      });
    }
  },
  {
    label: "订单商品",
    prop: "items",
    renderField(value: OrderItem[], onChange) {
      return h(ProductList, { products: value });
    }
  },
  {
    label: "贺卡内容",
    prop: "greeting_card",
    valueType: "textarea",
    colProps: {
      span: 12
    },
    fieldProps: {
      readonly: true,
      placeholder: "无内容"
    }
  },
  {
    label: "订单备注",
    prop: "notes",
    valueType: "textarea",
    colProps: {
      span: 12
    },
    fieldProps: {
      readonly: true,
      placeholder: "无内容"
    }
  },
  {
    label: "创建时间",
    prop: "created_on",
    renderField(value: string, onChange) {
      return h(ElInput, {
        modelValue: value ? dayjs(value).format("YYYY-MM-DD HH:mm:ss") : "",
        readonly: true
      });
    },
    colProps: {
      span: 12
    }
  },
  {
    label: "支付时间",
    prop: "payment_date",
    valueType: "tag",
    renderField(value: string, onChange) {
      return h(ElInput, {
        modelValue: value ? dayjs(value).format("YYYY-MM-DD HH:mm:ss") : "",
        readonly: true
      });
    },
    colProps: {
      span: 12
    }
  },
  {
    label: "配送员",
    prop: "delivery_person",
    renderField(value: { name: string; phone: string }) {
      return h(ElDescriptions, { border: true, column: 2 }, [
        h(ElDescriptionsItem, { label: "名字" }, () => value.name),
        h(ElDescriptionsItem, { label: "电话" }, () => value.phone),
        h(ElDescriptionsItem, { label: "配送地址" }, () => {
          const adr: any = formData.value.delivery_address;
          if (adr) {
            return `${adr.province} ${adr.city} ${adr.district} ${adr.details_address}`;
          }

          return "";
        })
      ]);
    },
    hideInForm: computed(() => !formData.value.delivery_person),
    colProps: {
      span: 24
    }
  }
];
const formVisible = ref(false);
const formData = ref<FieldValues>({});

const handleConfirm = () => {
  formVisible.value = false;
};

const handleSearch = e => {
  search();
};

const deliveryFormRules = {
  delivery_person: [
    {
      required: true,
      message: "请选择配送员"
    }
  ]
};

const deliveryFormColumns: PlusColumn[] = [
  {
    label: "配送员",
    prop: "delivery_person",
    valueType: "select",
    options: computed(() => {
      return deliveryPersonList.value.map(item => {
        return {
          label: item.name,
          value: item.id
        };
      });
    })
  }
];

const deliveryFormData = ref<FieldValues>({});
const deliveryFormVisible = ref<boolean>(false);
const deliveryFormSubmitting = ref<boolean>(false);
const deliveryPersonList = ref<DeliveryPerson[]>([]);

const loadDeliveryPerson = async () => {
  try {
    deliveryPersonList.value = await getAllDeliveryPerson();
  } catch (error) {
    console.log(error);
  }
};

onMounted(() => {
  loadDeliveryPerson();
});

const handleShowDelivery = () => {
  loadDeliveryPerson();
  deliveryFormData.value = {
    delivery_person: undefined
  };
  deliveryFormVisible.value = true;
};

const handleDelivery = async e => {
  try {
    const deliveryPerson = deliveryPersonList.value.find(
      item => item.id === e.delivery_person
    );

    if (deliveryPerson && formData.value.id) {
      await deliveryOrder({
        order_id: formData.value.id as number,
        delivery_person_id: deliveryPerson.id
      });
      formData.value = {
        ...formData.value,
        delivery_person: {
          name: deliveryPerson.name,
          phone: deliveryPerson.phone
        }
      };

      const response = await getOrderDetail(formData.value.id as number);
      formData.value = { ...response };
      refresh();

      message("操作成功", { type: "success" });
      deliveryFormVisible.value = false;
    }
  } catch (error) {
    message("操作失败", { type: "error" });
    console.log(error);
  }
};

const handleCloseOrder = async () => {
  try {
    state.formLoadingBtn = "close";
    if (formData.value && formData.value.id) {
      await closeOrder(formData.value.id as number);
    }
    const response = await getOrderDetail(formData.value.id as number);
    formData.value = { ...response };
    refresh();
    message("订单已关闭", { type: "success" });
  } catch (error) {
    message("关闭失败", { type: "error" });
  } finally {
    state.formLoadingBtn = null;
  }
};

const handleCompleteOrder = async () => {
  try {
    state.formLoadingBtn = "complete";
    if (formData.value && formData.value.id) {
      await completeOrder(formData.value.id as number);
    }
    const response = await getOrderDetail(formData.value.id as number);
    formData.value = { ...response };
    refresh();
    message("订单已完成", { type: "success" });
  } catch (error) {
    message("操作失败", { type: "error" });
  } finally {
    state.formLoadingBtn = null;
  }
};

const handleFefundOrder = async () => {
  try {
    state.formLoadingBtn = "refund";
    if (formData.value && formData.value.id) {
      await refundOrder(formData.value.id as number);
    }
    const response = await getOrderDetail(formData.value.id as number);
    formData.value = { ...response };
    refresh();
    message("已退款", { type: "success" });
  } catch (error) {
    message("操作失败", { type: "error" });
  } finally {
    state.formLoadingBtn = null;
  }
};
</script>
<template>
  <div>
    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between items-center">
          <span>订单管理</span>

          <el-space>
            <el-radio-group v-model="filter.order_status" @change="reload">
              <el-radio-button label="全部" :value="1" />
              <el-radio-button label="待支付" :value="2" />
              <el-radio-button label="待配送" :value="3" />
              <el-radio-button label="配送中" :value="4" />
            </el-radio-group>

            <el-input
              v-model="filter.kw"
              style="width: 240px"
              clearable
              placeholder="请输入订单号"
              @change="handleSearch"
            >
              <template #append>
                <IconifyIconOnline icon="ep:search" />
              </template>
            </el-input>
          </el-space>
        </div>
      </template>
      <pure-table
        ref="tableRef"
        border
        adaptive
        :adaptiveConfig="adaptiveConfig"
        row-key="id"
        alignWhole="center"
        showOverflowTooltip
        :loading="loading"
        :loading-config="loadingConfig"
        :data="dataList"
        :columns="columns"
        :pagination="pagination"
        @page-size-change="onSizeChange"
        @page-current-change="onCurrentChange"
      />
    </el-card>
    <PlusDialogForm
      v-model:visible="formVisible"
      v-model="formData"
      title="订单详情"
      :destroy-on-close="true"
      :form="{
        columns: formColumns,
        rules: formRules,
        labelPosition: 'top',
        rowProps: {
          gutter: 12
        }
      }"
    >
      <template #dialog-footer="{ handleCancel }">
        <el-space>
          <el-button
            v-if="
              formData.status === 1 &&
              formData.payment_status === 2 &&
              formData.shipping_status === 1
            "
            type="primary"
            :loading="state.formLoadingBtn === 'delivery'"
            :disabled="
              state.formLoadingBtn !== 'delivery' &&
              state.formLoadingBtn !== null
            "
            @click="handleShowDelivery"
          >
            开始配送
          </el-button>

          <el-popconfirm
            v-if="formData.status === 1 && formData.payment_status === 2"
            title="确认订单已完成?"
            :width="200"
            @confirm="handleCompleteOrder"
          >
            <template #reference>
              <el-button
                type="success"
                :loading="state.formLoadingBtn === 'complete'"
                :disabled="
                  state.formLoadingBtn !== 'complete' &&
                  state.formLoadingBtn !== null
                "
              >
                完成订单
              </el-button>
            </template>
          </el-popconfirm>

          <el-popconfirm
            v-if="formData.status === 1 && formData.payment_status === 1"
            title="确认关闭此订单?"
            :width="200"
            @confirm="handleCloseOrder"
          >
            <template #reference>
              <el-button
                type="warning"
                :loading="state.formLoadingBtn === 'close'"
                :disabled="
                  state.formLoadingBtn !== 'close' &&
                  state.formLoadingBtn !== null
                "
              >
                关闭订单
              </el-button>
            </template>
          </el-popconfirm>

          <el-popconfirm
            v-if="formData.status === 1 && formData.payment_status === 2"
            title="确认退款?"
            :width="200"
            @confirm="handleFefundOrder"
          >
            <template #reference>
              <el-button
                type="danger"
                :loading="state.formLoadingBtn === 'refund'"
                :disabled="
                  state.formLoadingBtn !== 'refund' &&
                  state.formLoadingBtn !== null
                "
              >
                退款
              </el-button>
            </template>
          </el-popconfirm>

          <el-button @click="handleCancel">取消</el-button>
        </el-space>
      </template>
    </PlusDialogForm>
    <PlusDialogForm
      v-model:visible="deliveryFormVisible"
      v-model="deliveryFormData"
      title="配送"
      width="480px"
      :destroy-on-close="true"
      :form="{
        columns: deliveryFormColumns,
        rules: deliveryFormRules,
        labelPosition: 'top'
      }"
      :confirm-loading="deliveryFormSubmitting"
      @confirm="handleDelivery"
    />
  </div>
</template>
